# -*- coding: utf-8 -*-
# +
import time
import sys,os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image #元组顺序为（R,G.B）
# basePath = os.path.split(os.path.realpath(__file__))[0]
# sys.path.append(basePath)
from functools import wraps
from multiprocessing import Pool
import multiprocessing

def timing(func):
    @wraps(func)
    def inner_func(*args, **kwargs):
        start = time.time()
        ans = func(*args, **kwargs)
        time_used = time.time() - start
        print('[INFO] function %s running time: %s s.'%(func.__name__, time_used))
        return ans
    return inner_func

def pool(func, iterable):
    p = Pool(min(len(iterable), multiprocessing.cpu_count()))
    r = p.starmap(func, iterable)
    return r

def ensure_folder(folder_name, clear=False):
    folder_name = str(folder_name)
    if clear and os.path.isdir(folder_name):
        shutil.rmtree(folder_name)
    if not os.path.isdir(folder_name):
        os.makedirs(folder_name)
        
def show_figure(y_test, predict, title='', xlabel='time',ylabel='value', labels=['ground_truth', 'predict'], save_path=None):
    y_test = np.array(y_test)#y_test.values
    title = title.replace('/','每')
    # 画拟合曲线
    plt.figure(figsize=(12,4))
    #plt.subplot(121)
    gap = max(1, len(y_test) // 300)
    plt.plot(y_test[::gap], color='green', label=labels[0], linewidth=1)
    plt.plot(predict[::gap], color='red', label=labels[1], linewidth=1)
#     plt.plot(predict[:200]-y_test[:200], color='red', label='residual', linewidth=1)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    # plt.text(0,0,text)
    plt.title(title)
    # plt.ylim(-1.2, 1.2)
    plt.legend()
    # plt.show()
    if save_path:
        plt.savefig(save_path)
    plt.close()

def concat_figures(figs, save_path):
    files = figs
    height, width, channel = np.array(Image.open(figs[0])).shape
    rows = (len(files)-1) // 3 + 1
    cols = (len(files)-1) % 3 + 1
    big_img = np.zeros((height*rows, width*cols, 4), dtype=np.int32)
    for i in range(len(files)):
        col = i % cols
        row = i // cols
        img = np.array(Image.open(figs[i]))[:,:,:]
        big_img[row*height:(row+1)*height, (col*width):((col+1)*width), :] = img
    big_img = Image.fromarray(big_img.astype(np.uint8))
    big_img.save(save_path)
    
def my_score(y_pred, y_test, suffix='', debug=False):
    y_test = np.array(y_test).reshape((-1,))
    maxError = (abs(y_test-y_pred)).max()
    MSE = (abs(y_test-y_pred)**2).mean()
    return {
        suffix+'maxError':[maxError],
        suffix+'MSE':[MSE],
    }
# -


